/**
 * 
 */
package climspace.client;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

import climspace.ejb.WeatherStationBean;

public class SjsuClientPortal {

	private Context ctx;
	private WeatherStationBean svc;
	private String host = "localhost";

	public void setHost(String host) {
		this.host = host;
	}

	private Context getContext() throws Exception {
		if (ctx != null)
			return ctx;

		Properties props = new Properties();
		props.put(Context.PROVIDER_URL, "jnp://" + host + ":1099");
		props.put(Context.INITIAL_CONTEXT_FACTORY,
				"org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES,
				"org.jboss.naming:org.jnp.interfaces");
		ctx = new InitialContext(props);

		return ctx;
	}

	private WeatherStationBean connectToService() throws Exception {
		if (svc != null)
			return svc;

		Context ctx = getContext();
		Object ref = ctx.lookup("WeatherStationBeanEJB/remote");
		svc = (WeatherStationBean) PortableRemoteObject.narrow(ref,
				WeatherStationBean.class);

		return svc;
	}

	public String getCurrentWeatherData(String stationId,
			String desiredOutputFormat) {
		String outputString = "";
		if (stationId == null)
			throw new RuntimeException("Missing primary_id");

		try {
			outputString = connectToService().getCurrentWeatherData(stationId,
					desiredOutputFormat);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return outputString;
	}
	public static void main(String[] args) {

		SjsuClientPortal climSpaceClient = new SjsuClientPortal();
		String outputString = climSpaceClient.getCurrentWeatherData("KIYA",
				"kmlOutputFormat");
		System.out.println(outputString);
	}
}
